package xu.ye.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import xu.ye.bean.ContactBean;
import xu.ye.view.adapter.ContactSelectAdapter;

import com.agent.crm.bean.MyContact;
import com.agent.crm.db.DBInitScript;
import com.agent.crm.db.DatabaseManager;
import com.agent.crm.view.R;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class ContactSelectActivity extends ListActivity{
    private LayoutInflater inflater;
    private Intent intent;
    private DatabaseManager manager = null;
    private ContactSelectAdapter adapter;
    private int groupId;
    private int typeId;
    private int position;
    private int workType = -1;
    public static final int WORK_TYPE_TYPE = 1;
    public static final int WORK_TYPE_GROUP = 2;
    
    public static final int EDIT_COTACT_RESULT_CODE = 1;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        intent = getIntent();
        groupId = intent.getIntExtra("group_id", -1);
        typeId = intent.getIntExtra("type_id", -1);
        position = intent.getIntExtra("position", -1);
        workType = intent.getIntExtra("work_type", -1);
        
        if(groupId == -1 && typeId == -1){
            return;
        }
        manager = new DatabaseManager(this);
        List<MyContact> list = new ArrayList<MyContact>();
        SQLiteDatabase database = manager.getWritableDatabase();
        Cursor cursor = null;
        StringBuilder sqlStr = new StringBuilder();
        if(workType == WORK_TYPE_TYPE){
            sqlStr.append("select c.contacts_id ,c.name, (select t.tc_id from " + DBInitScript.Table_Type_Middle + " t where t.typeid=? and t.contactsid=c.contacts_id limit 1 )");
            sqlStr.append(" from " + DBInitScript.Table_ContactsInfo + " c");
            cursor = database.rawQuery(sqlStr.toString(), new String[]{typeId + ""});
            
        }
        else if(workType == WORK_TYPE_GROUP){
            sqlStr.append("select c.contacts_id ,c.name, (select g.gc_id from " + DBInitScript.Table_Group_Middle + " g where g.groupid=? and g.contactsid=c.contacts_id limit 1 )");
            sqlStr.append(" from " + DBInitScript.Table_ContactsInfo + " c");
            cursor = database.rawQuery(sqlStr.toString(), new String[]{groupId + ""});
        }
        int count = cursor.getCount();
        if(count <= 0){
            return ;
        }
        cursor.moveToFirst();
        for(int i = 0; i < count; i++){
            cursor.moveToPosition(i);
            int contactsId =cursor.getInt(0);
            String name = cursor.getString(1);
            MyContact cb = new MyContact();
            cb.setContactsId(contactsId);
            cb.setName(name);
            if(workType == WORK_TYPE_TYPE){
                int tcId = cursor.getInt(2);
                if(tcId <= 0){
                    cb.setBelongType(0);
                }
                else{
                    cb.setBelongType(1);
                }
            }
            else if(workType == WORK_TYPE_GROUP){
                int gcId = cursor.getInt(2);
                if(gcId <= 0){
                    cb.setBelongGroup(0);
                }
                else{
                    cb.setBelongGroup(1);
                }
            }
            list.add(cb);
        }
        inflater = getLayoutInflater().from(this);
        
        adapter = new ContactSelectAdapter(this, inflater, list, workType);
        final ListView listView = getListView();
        listView.setAdapter(adapter);
        
        listView.setOnItemClickListener(contactItemClick);
        database.close();
    }

    
    OnItemClickListener contactItemClick = new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SQLiteDatabase dataBase = manager.getWritableDatabase();
            MyContact contact = (MyContact) adapter.getItem(position);
            int contactsId = contact.getContactsId();
            CheckBox checkBox = (CheckBox) view.findViewById(R.id.contactCheckBoxId);
            
            if(workType == WORK_TYPE_TYPE){
                int belongType = contact.getBelongType();
                if(belongType == 1){
                    //删除联系人
                    dataBase.delete(DBInitScript.Table_Type_Middle, "typeid=? and contactsid=?", 
                            new String[]{typeId + "", contactsId + ""});
                    contact.setBelongType(0);
                    checkBox.setChecked(false);
                }else{
                    //添加联系人
                    ContentValues value = new ContentValues();
                    value.put("contactsid", contactsId);
                    value.put("typeid", typeId);
                    dataBase.insert(DBInitScript.Table_Type_Middle, null, value);
                    contact.setBelongType(1);
                    checkBox.setChecked(true);
                }
            }
            else if(workType == WORK_TYPE_GROUP){
                int belongGroup = contact.getBelongGroup();
                if(belongGroup == 1){
                    //删除联系人
                    dataBase.delete(DBInitScript.Table_Group_Middle, "groupid=? and contactsid=?", 
                            new String[]{groupId + "", contactsId + ""});
                    contact.setBelongGroup(0);
                    checkBox.setChecked(false);
                }else{
                    //添加联系人
                    ContentValues value = new ContentValues();
                    value.put("contactsid", contactsId);
                    value.put("groupid", groupId);
                    dataBase.insert(DBInitScript.Table_Group_Middle, null, value);
                    contact.setBelongGroup(1);
                    checkBox.setChecked(true);
                }
            }
            dataBase.close();
            
        }
        
    };
    
    
    @Override
    protected void onDestroy() {
        
        if(manager != null){
            manager.close();
        }
        super.onDestroy();
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(workType == WORK_TYPE_TYPE){
                Bundle b = new Bundle();
                b.putInt("position", position);
                b.putInt("type_id", typeId);
                Intent intent = new Intent();
                intent.putExtras(b);
                setResult(EDIT_COTACT_RESULT_CODE, intent);
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    

}
